package com.soc.file.controller;
import com.soc.file.bean.FilePO;
import com.soc.file.bean.Result;
import com.soc.file.servie.ChunkService;
import com.soc.file.servie.FileService;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@CrossOrigin
@RequestMapping("/file")
public class FileController {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${file.path}")
    private String filePath;

    @Autowired
    private FileService fileService;
    @Autowired
    private ChunkService chunkService;

    @GetMapping("/check")
    public Result checkFile(@RequestParam("md5") String md5 ){
        logger.info("检查MD5:"+md5);
        //首先检查是否有完整的文件
//        String  fileUrl  = "http://49.234.41.23:8998/file/fileUrl/"+fileName;

       Boolean isUploaded = fileService.selectFileByMd5(md5);
        Map<String, Object> data = new HashMap<>();
       data.put("isUploaded",isUploaded);
       //如果有，就返回秒传
       if(isUploaded){
          FilePO s = fileService.selectFileNameByMd5(md5);
           String name = s.getName();
           String  fileUrl  = "/api/file/fileUrl/"+name;
            return new Result(200,"文件已经秒传",fileUrl);
       }

        //如果没有，就查找分片信息，并返回给前端
        List<Integer> chunkList = chunkService.selectChunkListByMd5(md5);
        data.put("chunkList",chunkList);

        return  new Result(200,"",data);
    }

    @PostMapping("/upload/chunk")
    public Result uploadChunk(@RequestParam("chunk") MultipartFile chunk,
                              @RequestParam("md5") String md5,
                              @RequestParam("index") Integer index,
                              @RequestParam("chunkTotal")Integer chunkTotal,
                              @RequestParam("fileSize")Long fileSize,
                              @RequestParam("fileName")String fileName,
                              @RequestParam("chunkSize")Long chunkSize
    ){
        String[] splits = fileName.split("\\.");
        String type = splits[splits.length-1];
        String resultFileName = filePath+fileName;

        chunkService.saveChunk(chunk,md5,index,chunkSize,resultFileName);
        logger.info("上传分片："+index +" ,"+chunkTotal+","+fileName+","+resultFileName);
        String  fileUrl  = "/api/file/fileUrl/"+fileName;
        if(Objects.equals(index, chunkTotal)){
            FilePO filePO = new FilePO(fileName, md5, fileSize);
            fileService.addFile(filePO);
            chunkService.deleteChunkByMd5(md5);
            return  new Result(200,"文件上传成功",fileUrl);
        }else{
            return new Result(200,"分片上传成功",fileUrl);
        }

    }

    @GetMapping("/fileList")
    public Result getFileList(){
        logger.info("查询文件列表");
        List<FilePO> fileList = fileService.selectFileList();

        return  new Result(200,"文件列表查询成功",fileList);
    }


//     return ResponseEntity.ok()
//             .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
//            .body(resource);

    @GetMapping("/fileUrl/{filename}")
    public ResponseEntity<Resource> downloadFile(@PathVariable  String filename) throws MalformedURLException {
        File file = new File(filePath+filename);
        Resource resource = new UrlResource(file.toURI().toURL());
        String url = filePath +filename;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/octet-stream"));
        headers.setContentDispositionFormData(resource.getFilename(), resource.getFilename());
        return new ResponseEntity<>(resource, headers, HttpStatus.OK);

    }

    @PostMapping("/DeleteFile")
    public Result DeleteFile(@RequestParam("md5") String md5){
        fileService.deleteFileByMd5(md5);
        Map<String, Object> data = new HashMap<>();

        return new Result(200,"删除成功",data);
    }

    @DeleteMapping ("/fileUrl/{filename}")
    public Boolean deleteFile(@PathVariable  String filename) throws MalformedURLException {
        File file = new File(filePath+filename);
        Resource resource = new UrlResource(file.toURI().toURL());
        String url = filePath +filename;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/octet-stream"));
        headers.setContentDispositionFormData(resource.getFilename(), resource.getFilename());

        if (file.exists()) {
            return file.delete();
        }

        return false;
    }



    }


